﻿using KongMing.WebTools.Common;
using KongMing.WebTools.Models;
using Microsoft.AspNetCore.Mvc;
using System.Text;
using Newtonsoft.Json;
using KongMing.WebTools.Service;
using System.Linq;

namespace KongMing.WebTools.Controllers
{
    public class WebToolsController : Controller
    {
        public IActionResult OrmTool()
        {
            string ormTypeOptions = "";
            string sqlTypeOptions = "";
            string scanTypeOptions = "";
            foreach (var type in SqlType.GetSqlTypes())
            {
                sqlTypeOptions += $"<option value='{type}'>{type}</option>";
            }
            foreach (var enumdic in Helper.GetOrmTypes())
            {
                ormTypeOptions += $"<option value='{enumdic.Key}'>{enumdic.Value}</option>";
            }
            foreach (var enumdic in Helper.GetExpandScanTypes())
            {
                scanTypeOptions += $"<option value='{enumdic.Key}'>{enumdic.Value}</option>";
            }
            ViewData["sqlTypeOptions"] = sqlTypeOptions;
            ViewData["ormTypeOptions"] = ormTypeOptions;
            ViewData["scanTypeOptions"] = scanTypeOptions;
            return View();
        }

        [HttpPost]
        public async Task<ApiResult> BuildDataAsync(OrmModel table)
        {
            try
            {
                if (table == null || string.IsNullOrWhiteSpace(table.TableName))
                    throw new Exception("参数不能为空！");
                table!.Fields.RemoveAll(x => string.IsNullOrWhiteSpace(x.FieldName));
                if (table?.Fields?.Count == 0)
                    throw new Exception("请至少输入一个字段！");
                DataFormat.FixOrmModelData(table!);//处理数据格式
                var sqlBuilder = new SqlBuilder(table!.Clone());
                var ormBuilder = new OrmBuilder(table!.Clone());
                
                var tasks = new Task<string>[]
                {
                    Task.Run(() => sqlBuilder.BuildSqlTable()),
                    Task.Run(() => ormBuilder.BuildOrmEntity())
                };
                await Task.WhenAll(tasks);
                var result = new ApiResult
                {
                    code = 0,
                    message = "请求成功！",
                    data = new OrmToolResult
                    {
                        SqlData = tasks[0].Result,
                        OrmData = tasks[1].Result
                    }
                };
                return result;
            }
            catch (Exception ex)
            {
                var result = new ApiResult
                {
                    code = -1,
                    message = "请求失败！错误信息：" + ex.Message,
                    data = null
                };
                return result;
            }
        }
    }
}
